// subHoliday/root/addMenu/optMenu.js
import {
  identity,
  level,
  debounce,
  splitBase64IntoChunks
} from '../../../utils/util'
const appg = getApp().globalData
Page({

  /**
   * 页面的初始数据
   */
  data: {
    show: false,
    columns: [],
    json: null,
    loading: false,
    opt_name: null,
    updateID: null,
    // 展示用的
    form: {
      menuName: null,
      identityID: null,
      level: null,
      imgUrl: [],
      parents_id: '自身',
      route: null
    },
    // 上传用的
    uploadForm: {
      menuName: null,
      identityID: null,
      level: null,
      imgUrl: null,
      parents_id: 0,
      route: null
    }
  },
  // 打开popup
  async showPicker(e) {
    console.log(e.currentTarget.dataset.optname);
    let opt_name = e.currentTarget.dataset.optname;
    this.setData({
      opt_name,
      loading: true,
      show: true
    })
    switch (opt_name) {
      case 'identityID':
        this.setData({
          columns: identity,
          loading: false
        })
        break;
      case 'level':
        this.setData({
          columns: level,
          loading: false
        })
        break;
      default:
         await this.getParentMent();
        let data = []
        this.data.json.forEach(item => {
          data.push(item.menuName)
        });
        this.setData({
          columns: data,
          loading: false,
        })
        break;
    }
  },
  async getParentMent() {
    // 获取当前有的模块
    try {
      let json = await getApp().$axios("/getParentMenu", "GET")
      console.log(json);
      if (json.status !== 200) {
        wx.showToast({
          title: json.msg,
          icon: 'error'
        })
        return
      }
      this.setData({
        json: json.data
      })
    } catch (error) {
      wx.showToast({
        title: error.msg,
        icon: 'error'
      })
    }
  },
  // 关闭
  onCancel() {
    this.setData({
      show: false
    })
  },
  // 确认选择
  onConfirm(e) {
    console.log(e.detail);
    const {
      index,
      value
    } = e.detail;
    const formName = 'form.' + this.data.opt_name
    const UploadForm = 'uploadForm.' + this.data.opt_name
    if (this.data.opt_name == "parents_id") {
      let parents_id = this.data.json[index].id
      this.setData({
        [formName]: value,
        [UploadForm]: parents_id,
        show: false
      })
    } else if (this.data.opt_name == "level") {
      this.setData({
        [formName]: value,
        [UploadForm]: index,
        show: false
      })
    } else {
      this.setData({
        [formName]: value,
        [UploadForm]: index + 1,
        show: false
      })
    }
  },
  // 处理输入的
  handleInput: debounce(function (e) {
    let value = e.detail;
    let form = 'form.' + e.currentTarget.dataset.optname;
    let uploadForm = 'uploadForm.' + e.currentTarget.dataset.optname;
    this.setData({
      [form]: value,
      [uploadForm]: value
    })
  }, 500),
  // 提交
  async handleSubmit() {
    let code = "/addMenu"
    if (this.data.uploadForm.id) {
      code = '/updateMenu'
    }
    try {
      const json = await getApp().$axios(code, "POST", this.data.uploadForm);
      console.log(json);
      if (json.status !== 200) {
        wx.showToast({
          title: json.data,
          icon: 'none'
        })
        return
      }
      wx.showToast({
        title: json.data,
        icon: 'success'
      })
      wx.navigateBack({
        delta: 1,
      })
    } catch (error) {
      wx.showToast({
        title: error.msg,
        icon: 'error'
      })
    }
  },
  // 图片上传
  async handleImageUpload(e) {
    console.log(e.detail.file.url);
    let imgUrl = e.detail.file.url
    // let imgType = null;
    // // 如果需要获取图片类型的话
    // wx.getImageInfo({
    //   src: imgUrl,
    //   success(res) {
    //     console.log(res);
    //     imgType = res.type
    //   }
    // });
    let imgBase64 = null;
    const fs = wx.getFileSystemManager()
    // 同步接口
    try {
      const res = fs.readFileSync(imgUrl, 'base64', 0)
      console.log("图片的base64：", res)
      imgBase64 = res
    } catch (e) {
      wx.showToast({
        title: e,
      })
    }
    // 分块
    let chunks = splitBase64IntoChunks(imgBase64, 1024 * 64)
    // 删除 "http://"  
    imgUrl = imgUrl.replace("http://", "");
    // // 删除文件的扩展名，包括 "."  
    // imgName = imgName.replace(/\.[^.]+$/, "");
    const socket = wx.connectSocket({
      url: appg.ws,
      success() {
        console.log("socket 服务器连接成功");
      },
      fail() {
        console.log("socket 服务器连接失败");
      }
    });
    socket.onOpen((res) => {
      socket.send({
        data: JSON.stringify({
          event: 'imgName',
          data: imgUrl
        })
      });
      console.log("onOpen", res);
      socket.onMessage(async (data) => {
        const json = JSON.parse(data.data)
        console.log("服务器返回来的数据:", json);
        if (json.event == "sentImgUrl") {
          console.log(json.data.imgUrl, "图片在线地址");
          const uploadUrl = 'https://' + json.data.imgUrl
          const Url = {
            url: uploadUrl
          }
          this.data.form.imgUrl.push(Url)
          this.setData({
            'uploadForm.imgUrl': uploadUrl,
            'form.imgUrl': this.data.form.imgUrl
          })
          // 关闭连接
          socket.close({
            code: 1000
          })
        }
      });
      // 逐个发送块数据
      chunks.forEach((chunk, index) => {
        let eventData = {
          event: 'base64Data', // 事件标识字段
          data: chunk
        };
        setTimeout(() => {
          socket.send({
            data: JSON.stringify(eventData),
            success: () => {
              console.log(`块 ${index + 1}/${chunks.length} 已发送`);
              if (index === chunks.length - 1) {
                // 所有块数据已发送，发送结束消息
                socket.send({
                  data: JSON.stringify({
                    data: {},
                    event: 'upload_complete'
                  }),
                  success: () => {
                    console.log('上传完成');
                    // 关闭定时器或执行其他操作
                    wx.hideLoading()
                  },
                });
              };
            },
          });
        }, index * 200); // 延迟发送以避免过快发送
      });

      socket.onError((error) => {
        console.log("错误信息：", error);
      });
      socket.onClose((code, reason) => {
        console.log("一个数字值表示关闭连接的状态号，表示连接被关闭的原因。:", code, "表示连接被关闭的原因。", reason);
      })
    })
  },
  // 图片删除
  deleteIcon(e){
    console.log(e.detail.index,e);
    this.setData({
      'form.imgUrl':[],
      'uploadForm.imgUrl':null
    })
  },
  // 根据id查菜单 修改！
  async queryMenuById(mid) {
    /**
     *menuName: null,
      identityID: null,
      level: null,
      imgUrl: null,
      parents_id: 0,
      route: null
     */
    try {
      const json = await getApp().$axios("/getMenuById?id=" + mid, "GET")
      if (json.status !== 200) {
        wx.showToast({
          title: json.data,
          icon: 'error'
        })
        return
      }
      console.log(json);
      const {
        id,
        menuName,
        identityID,
        level,
        imgUrl,
        parents_id,
        route
      } = json.data
      let parentsName =await this.getParentName(parents_id)
      const formdata = {
        menuName,
        identityID: identityID == 1 ? "学生" : identityID == 2 ? '老师' : '超级管理员',
        level: level == 0 ? "否" : "是",
        imgUrl: [{
          url: imgUrl
        }],
        parents_id:parentsName,
        route
      }
      console.log(formdata);
      Object.assign(this.data.uploadForm, json.data)
      this.setData({
        updateID: id,
        form: formdata,
        uploadForm: this.data.uploadForm
      })

    } catch (error) {
      wx.showToast({
        title: error.msg,
        icon: 'error'
      })
    }
  },
  // 根据id查属于哪个模块
   async getParentName(key) {
    console.log("进来了",key,this.data.json);
    if (key==0) {
      return "自身"
    }
    await this.getParentMent()
    const arr = this.data.json.filter(item => {
      return item.id == key
    });
    console.log(arr);
    return arr[0].menuName;
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    console.log(options.id);
    // 如果有说明是修改 没有就是添加
    if (options.id) {
      const id = options.id;
      this.queryMenuById(id)
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})